#!/bin/bash
# Intro:
#    run under root
# Change Log:
# 2024-01-20 Wanli Xing<xingwanli@outlook.com>
# * Create and test in servera
echo -e "\e[32m Install apache httpd and gitweb package...\e[0m"
echo ""
dnf install gitweb httpd -y  >/dev/null
sleep 3

echo -e "\e[32m Custom gitweb virtualhost site config...\e[0m"
echo ""
cat > /etc/httpd/conf.d/gitweb.conf <<-EOF
Listen 8080
<virtualhost *:8080>
        ServerName $HOSTNAME:8080
        DocumentRoot /var/www/git/
        ErrorLog /var/log/httpd/git_error.log
        CustomLog /var/log/httpd/git_access.log combined
</virtualhost>


<Directory /var/www/git>
  Options +ExecCGI
  AddHandler cgi-script .cgi
  DirectoryIndex gitweb.cgi

  # nice friendly URL's for browsing branches
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^.* /gitweb.cgi/$0 [L,PT]
</Directory>


ScriptAliasMatch \\
"(?x)^/(.*/(HEAD | \\
info/refs | \\
objects/(info/[^/]+ | \\
[0-9a-f]{2}/[0-9a-f]{38} | \\
pack/pack-[0-9a-f]{40}\.(pack|idx)) | \\
git-(upload|receive)-pack))$" \\
/usr/libexec/git-core/git-http-backend/\$1

SetEnv GIT_PROJECT_ROOT /var/www/git/pub
SetEnv GIT_HTTP_EXPORT_ALL
SetEnv REMOTE_USER=\$REDIRECT_REMOTE_USER

<Location />
        Require all granted
</Location>

EOF

echo -e "\e[32m Prepare git repo directory...\e[0m"
echo ""
mkdir /var/www/git/pub
chmod 2775 /var/www/git/pub
chown -R apache:apache /var/www/git/pub
semanage fcontext -a -t git_rw_content_t "/var/www/git/pub(/.*)?"
restorecon -RvvF /var/www/git/pub &>/dev/null
sed -i 's/our $projectroot = "\/var\/lib\/git"/our $projectroot = "\/var\/www\/git\/pub"/g' /var/www/git/gitweb.cgi

echo -e "\e[32m Starting httpd web server...\e[0m"
echo ""
systemctl enable httpd.service --now --quiet
ZONE=$(firewall-cmd --get-default-zone) firewall-cmd --add-port=8080/tcp --zone=${ZONE} --permanent  &>/dev/null
firewall-cmd --reload &>/dev/null


# echo -e "\e[32m Create helloworld git repo...\e[0m"
# echo ""
# tar -xf rh294_v8.tar.gz -C /


echo -e "\e[32m Git Server has sucessfully...\e[0m"
